<?php
namespace app\index\controller;

class User extends Common
{
    //会员中心页面
    public function index()
    {
        $user_id = session('id');
        $dingdanlist = db('dingdan')->where("user_id=$user_id")->limit(2)->select();
        // dump($dingdanlist);die;
        $goodslist = db('dingdan_goods')->alias('a')->join('goods b','a.goods_id=b.id')->join('goods_attributes c','a.attributes_id=c.id')->join('goods_guigetype d','c.guigeType_id=d.id')->field('a.dingdan_id,a.goods_id,a.num,b.name,b.thumb_src,c.price,d.name as guigetypeName,d.pid')->select();
        // dump($goodslist);die;
        $color_list = db('goods_guigetype')->select();
        //数组重组,取规格颜色
        foreach($goodslist as $k1 => $v1){
            foreach($color_list as $k2 =>$v2){
                if($v1['pid']==$v2['id']){
                    $goodslist[$k1]['guigetypeName']=[
                        'father'=>$v2['name'],
                        'son'=>$v1['guigetypeName']
                    ];
                    unset($goodslist[$k1]['pid']);
                }
            }
            $goodslist[$k1]['price'] = number_format((float)$v1['price'],2);
        }
        // dump($goodslist);die;
        //合并规格数组为字符串
        foreach($goodslist as $k1 =>$v1){
            foreach($goodslist as $k2 => $v2){
                if(is_array($v2['guigetypeName'])){
                    //数组转字符串
                    $guigetypeName = implode(' , ',$goodslist[$k2]['guigetypeName']);
                    $goodslist[$k2]['guigetypeName'] = $guigetypeName;
                }
            }
        }
        // dump($goodslist);die;
        //取第一张图片
        foreach($goodslist as $val){
            $thumb_src = json_decode($val['thumb_src'],true);
            if($thumb_src!=NULL){
                $val['thumb_src']=array($thumb_src[0]);
            }else{
                $val['thumb_src']=array($val['thumb_src']);
            }
            $row[] = $val;
        }
        // dump($row);die;
        $list = $dingdanlist;
        foreach($list as $k1 =>$v1){
            foreach($row as $k2 => $v2){
                if($v2['dingdan_id']!='' && $v2['dingdan_id']==$v1['id']){
                    $list[$k1]['son'][]=$v2;
                }
            }
            //金额三位一逗号，保留小数点后两位
            $list[$k1]['total_money'] = number_format((float)$v1['total_money'],2);
        }
        //优惠券列表
        $user_id = session('id');
        $coupon_list = db('coupon_user')->alias('a')->join('coupon b','a.coupon_id=b.id')->field('b.*')->where("a.user_id={$user_id}")->order('b.id asc')->limit(3)->select();       
        $this->assign('coupon_list',$coupon_list);

        $this->assign('list',$list);
        return view();
    }
    
    public function dingdan()
    {
        $user_id = session('id');
        $dingdanlist = db('dingdan')->where("user_id=$user_id")->select();
        // dump($dingdanlist);die;
        $goodslist = db('dingdan_goods')->alias('a')->join('goods b','a.goods_id=b.id')->join('goods_attributes c','a.attributes_id=c.id')->join('goods_guigetype d','c.guigeType_id=d.id')->field('a.dingdan_id,a.goods_id,a.num,b.name,b.thumb_src,c.price,d.name as guigetypeName,d.pid')->select();
        // dump($goodslist);die;
        $color_list = db('goods_guigetype')->select();
        //数组重组,取规格颜色
        foreach($goodslist as $k1 => $v1){
            foreach($color_list as $k2 =>$v2){
                if($v1['pid']==$v2['id']){
                    $goodslist[$k1]['guigetypeName']=[
                        'father'=>$v2['name'],
                        'son'=>$v1['guigetypeName']
                    ];
                    unset($goodslist[$k1]['pid']);
                }
            }
            $goodslist[$k1]['price'] = number_format((float)$v1['price'],2);
        }
        // dump($goodslist);die;
        //合并规格数组为字符串
        foreach($goodslist as $k1 =>$v1){
            foreach($goodslist as $k2 => $v2){
                if(is_array($v2['guigetypeName'])){
                    //数组转字符串
                    $guigetypeName = implode(' , ',$goodslist[$k2]['guigetypeName']);
                    $goodslist[$k2]['guigetypeName'] = $guigetypeName;
                }
            }
        }
        // dump($goodslist);die;
        //取第一张图片
        foreach($goodslist as $val){
            $thumb_src = json_decode($val['thumb_src'],true);
            if($thumb_src!=NULL){
                $val['thumb_src']=array($thumb_src[0]);
            }else{
                $val['thumb_src']=array($val['thumb_src']);
            }
            $row[] = $val;
        }
        // dump($row);die;
        $list = $dingdanlist;
        foreach($list as $k1 =>$v1){
            foreach($row as $k2 => $v2){
                if($v2['dingdan_id']!='' && $v2['dingdan_id']==$v1['id']){
                    $list[$k1]['son'][]=$v2;
                }
            }
            //金额三位一逗号，保留小数点后两位
            $list[$k1]['total_money'] = number_format((float)$v1['total_money'],2);
        }
        // dump($list);die;
        $this->assign('list',$list);
        return view();
    }
    
    //确认收货
    public function shouhuo()
    {
        $id = input('post.dingdan_id');
        // dump($id);die;
        $data = [
            'queren_status' => 1,
        ];
        $ret = db('dingdan')->where("id={$id}")->update($data);
        if($ret==false){
            $this->error('确认失败','',0);
        }else{
            $this->success('确认成功','',1);
        }
    }

    //地址列表
    public function address()
    {
        $user_id = session('id');
        $list = db('user_address')->alias('a')->join('user b','a.user_id=b.id')->field('a.*,b.address_id')->where("user_id=$user_id")->select();
        $this->assign('list',$list);
        return view();
    }

    //地址添加页面
    public function add()
    {
        return view();
    }

    //地址修改页面
    public function edit()
    {
        $id = input('get.id');      
        // dump($id);die;
        $list = db('user_address')->alias('a')->join('user b','a.user_id=b.id')->field('a.*,b.address_id')->where("a.id=$id")->find();
        // dump($list);die;
        $this->assign('list',$list);

        return view();
    }

    //添加新地址
    public function insert()
    {
        $user_id = session('id');
        $shouhuo_name = input('post.shouhuo_name');
        $shouhuo_tell = input('post.shouhuo_tell');
        $shouhuo_address = input('post.shouhuo_address');

        $data=[
            'user_id' => $user_id,
            'shouhuo_address' => $shouhuo_address,
            'shouhuo_tell' => $shouhuo_tell,
            'shouhuo_name' => $shouhuo_name,
        ];

        $ret = db('user_address')->insert($data);
        if($ret==false){
            $this->error('添加失败');
        }else{
            $this->success('添加成功','user/address');
        }
    }

    //修改地址
    public function update()
    {
        $id = input('get.id');
        // dump($id);die;
        $data = input('post.');
        // dump($data);die;

        $ret = db('user_address')->where("id='{$id}'")->update($data);
        if($ret==false){
            $this->error('修改失败');
        }else{
            $this->success('修改成功','user/address');
        }
    }

    //删除地址
    public function delete()
    {
        $id = input('get.id');
        // dump($id);die;
        $ret = db('user_address')->where("id={$id}")->delete();
        if($ret==false){
            $this->error('删除失败');
        }else{
            $this->success('删除成功','user/address');
        }
    }

    public function addmoren()
    {
        $address_id = input('post.address_id');
        $user_id = input('post.user_id');
        $data = [
            'address_id' => $address_id,
        ];
        $result = db('user')->where("id='$user_id'")->update($data);
        if($result==false){
            $this->error('当前已为默认地址');
        }else{
            $this->success('设置成功');
        }
    }

    //我的优惠券页面
    public function mycoupon()
    {    
        $user_id = session('id');
        $coupon_list = db('coupon_user')->alias('a')->join('coupon b','a.coupon_id=b.id')->field('b.*')->where("a.user_id={$user_id}")->order('b.id asc')->select();   
        $this->assign('coupon_list',$coupon_list);
        return view();
    }

    //修改个人资料页面
    public function editUser()
    {        
        return view('edit-user');
    }

    //修改提交
    public function updateUser()
    {
        $user_id = session('id');
        $data = input('post.');         
        $validate = validate('Edituser');       //加载验证器
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        if($data['tellcode'] != session('tell_code')['code'] || $data['tell'] != session('tell_code')['tell']){
            $this->error("短信验证码错误！");
        }
        unset($data['repwd']);
        unset($data['tellcode']);
        unset($data['tell']);

        $ret = db('user')->where("id={$user_id}")->update($data);
        if($ret == false){
            $this->error("修改失败！");
        }else{
            $this->success("修改成功,请重新登录!",'index/login/logout');
        }
    }
    //修改头像
    public function editHeadimg()
    {        
        return view('edit-headimg');
    }
    //修改提交
    public function updateHeadimg()
    {
        $user_id = session('id');
        $data = input('post.'); 
        if(empty($data['headimg_url'])){
            $this->error("图片未选择!");
        }
        unset($data['src']);
        $ret = db('user')->where("id={$user_id}")->update($data);        
        if($ret == false){
            $this->error("修改失败！");
        }else{
            session('head_img',$data['headimg_url']);
            $this->success("修改成功",'index/user/index');
        }
    }
    //上传轮播图
    public function upimg(){
        $file = request()->file('src');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $img_src = '/uploads/'.$info->getSaveName();
                //制作缩略图
                //打开图片
                $image = \think\Image::open('.'.$img_src);
                $date =date('Ymd',time());
                $path="uploads/thumbs/$date";
                if(!file_exists($path)){
                    mkdir($path, 0777,true);
                }
                //保存缩略图 前面要加点
                $image->thumb(150,100)->save('.'.'/uploads/thumbs/'.$info->getSaveName());
                $thumb_src='/uploads/thumbs/'.$info->getSaveName();
                return ['src'=>$img_src,'thumb_src'=>$thumb_src];
            }
        }
        else{
            $this->error($file->getError());
        }
    }
}